#!/usr/bin/env python3
"""
纯 Python 镜像工具 - 不依赖外部库
使用内置的 urllib
"""

import argparse
import sys
import urllib.request
import urllib.error
from urllib.parse import urlparse

class SimpleMirrorManager:
    def __init__(self):
        pass
    
    def check_mirror_gitee(self, mirror_url):
        """使用 HTTP 检查 Gitee 镜像"""
        print(f"🔍 检查镜像: {mirror_url}")
        
        try:
            # 解析 URL
            parsed = urlparse(mirror_url)
            if 'gitee.com' not in parsed.netloc:
                print("   ⚠️  仅支持 Gitee 镜像检查")
                return False
            
            # 构造 Gitee 项目页面 URL
            path_parts = parsed.path.strip('/').split('/')
            if len(path_parts) >= 2:
                owner = path_parts[0]
                repo = path_parts[1].replace('.git', '')
                
                # 直接访问项目页面
                page_url = f"https://gitee.com/{owner}/{repo}"
                print(f"   访问: {page_url}")
                
                # 设置请求头
                headers = {
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
                }
                
                req = urllib.request.Request(page_url, headers=headers)
                response = urllib.request.urlopen(req, timeout=10)
                
                if response.getcode() == 200:
                    html_content = response.read().decode('utf-8', errors='ignore')
                    
                    # 简单检查页面内容
                    if '仓库不存在' in html_content or '404' in html_content:
                        print("   ❌ 镜像不存在")
                        return False
                    else:
                        print("   ✅ 镜像存在（页面可访问）")
                        return True
                else:
                    print(f"   ❌ HTTP 错误: {response.getcode()}")
                    return False
            else:
                print("   ❌ 无效的 Gitee URL")
                return False
                
        except urllib.error.HTTPError as e:
            if e.code == 404:
                print("   ❌ 镜像不存在 (404)")
            else:
                print(f"   ❌ HTTP 错误: {e.code}")
            return False
        except urllib.error.URLError as e:
            print(f"   ❌ 网络错误: {e.reason}")
            return False
        except Exception as e:
            print(f"   ❌ 检查失败: {e}")
            return False
    
    def check_mirror_github(self, original_url):
        """检查原始 GitHub 仓库"""
        print(f"🔍 检查原始仓库: {original_url}")
        
        try:
            parsed = urlparse(original_url)
            if 'github.com' not in parsed.netloc:
                print("   ⚠️  仅支持 GitHub 原始仓库检查")
                return True  # 假设存在
            
            path_parts = parsed.path.strip('/').split('/')
            if len(path_parts) >= 2:
                owner = path_parts[0]
                repo = path_parts[1].replace('.git', '')
                
                page_url = f"https://github.com/{owner}/{repo}"
                print(f"   访问: {page_url}")
                
                headers = {
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
                }
                
                req = urllib.request.Request(page_url, headers=headers)
                response = urllib.request.urlopen(req, timeout=10)
                
                if response.getcode() == 200:
                    print("   ✅ 原始仓库存在（页面可访问）")
                    return True
                else:
                    print(f"   ⚠️  HTTP 错误: {response.getcode()}")
                    return True  # 假设存在
            else:
                print("   ❌ 无效的 GitHub URL")
                return True  # 假设存在
                
        except urllib.error.HTTPError as e:
            if e.code == 404:
                print("   ⚠️  原始仓库不存在 (404)")
            else:
                print(f"   ⚠️  HTTP 错误: {e.code}")
            return True  # 假设存在
        except Exception as e:
            print(f"   ⚠️  原始仓库检查失败: {e}")
            return True  # 假设存在
    
    def setup_mirror_config(self, original_url, mirror_url):
        """生成镜像配置说明"""
        print("🎯 镜像配置说明")
        print("=" * 60)
        print(f"原始仓库: {original_url}")
        print(f"镜像仓库: {mirror_url}")
        print()
        print("请执行以下 git 命令配置镜像:")
        print()
        print(f'git config --local url."{mirror_url}".insteadOf "{original_url}"')
        print()
        print("配置完成后，运行以下命令初始化子模块:")
        print("git submodule update --init --recursive")
        print()
        print("要验证配置，可以运行:")
        print("git config --local --list | findstr insteadOf")
        print("=" * 60)
        return True

def main():
    parser = argparse.ArgumentParser(description='纯 Python 镜像工具 (无外部依赖)')
    subparsers = parser.add_subparsers(dest='command', help='子命令')
    
    # check 命令
    check_parser = subparsers.add_parser('check', help='检查镜像')
    check_parser.add_argument('mirror_url', help='镜像URL')
    
    # compare 命令
    compare_parser = subparsers.add_parser('compare', help='比较镜像和原始仓库')
    compare_parser.add_argument('original_url', help='原始URL')
    compare_parser.add_argument('mirror_url', help='镜像URL')
    
    # setup 命令 - 修复语法错误
    setup_parser = subparsers.add_parser('setup', help='生成镜像配置说明')
    setup_parser.add_argument('original_url', help='原始URL')
    setup_parser.add_argument('mirror_url', help='镜像URL')
    
    # batch 命令
    batch_parser = subparsers.add_parser('batch', help='批量生成配置说明')
    batch_parser.add_argument('--wx', action='store_true', help='生成 wxWidgets 配置')
    
    args = parser.parse_args()
    
    if not args.command:
        parser.print_help()
        return
    
    manager = SimpleMirrorManager()
    
    if args.command == 'check':
        success = manager.check_mirror_gitee(args.mirror_url)
        sys.exit(0 if success else 1)
    
    elif args.command == 'compare':
        print("=== 仓库比较 ===")
        original_ok = manager.check_mirror_github(args.original_url)
        print()
        mirror_ok = manager.check_mirror_gitee(args.mirror_url)
        print()
        
        if original_ok and mirror_ok:
            print("✅ 两个仓库都存在，可以配置镜像")
        else:
            print("⚠️  镜像检查失败，但您仍然可以尝试配置")
        
        sys.exit(0 if mirror_ok else 1)
    
    elif args.command == 'setup':
        success = manager.setup_mirror_config(args.original_url, args.mirror_url)
        sys.exit(0 if success else 1)
    
    elif args.command == 'batch':
        print("=== wxWidgets 子模块镜像配置 ===")
        print()
        
        mirrors = [
            ("expat", "https://github.com/libexpat/libexpat", "https://gitee.com/mirrors/expat"),
            ("zlib", "https://github.com/madler/zlib", "https://gitee.com/mirrors/zlib"),
            ("libpng", "https://github.com/glennrp/libpng", "https://gitee.com/mirrors/libpng"),
            ("libtiff", "https://gitlab.com/libtiff/libtiff", "https://gitee.com/mirrors/libtiff"),
            ("libjpeg-turbo", "https://github.com/libjpeg-turbo/libjpeg-turbo", "https://gitee.com/mirrors/libjpeg-turbo")
        ]
        
        print("请执行以下命令配置所有镜像:")
        print()
        for name, original, mirror in mirrors:
            print(f'git config --local url."{mirror}".insteadOf "{original}"')
        print()
        print("然后运行:")
        print("git submodule update --init --recursive")
        print()
        print("=" * 60)

if __name__ == '__main__':
    main()
